<!-- src/views/LoginRegisterView.vue -->
<template>
  <el-container class="login-register-container">
    <img :src="backgroundImg" alt="登录背景" class="background-img" />
    <el-card class="login-card">
      <div class="login-card-header">
        <img src="@/assets/buddy_logo.png" alt="友友学社 Logo" class="login-logo" />
        <h2>欢迎来到友友学社</h2>
        <p>请登录或注册以继续</p>
      </div>

      <!-- Tab 切换：登录和注册 -->
      <el-tabs v-model="activeTab" @tab-click="handleTabClick" stretch>
        <el-tab-pane label="登录" name="login">
          <!-- 登录模式切换，使用面包屑样式 -->
          <el-breadcrumb separator="|">
            <el-breadcrumb-item @click="changeLoginMode('username')">
              <span :class="{'breadcrumb-active': loginMode === 'username'}">用户名密码登录</span>
            </el-breadcrumb-item>
            <el-breadcrumb-item @click="changeLoginMode('phone')">
              <span :class="{'breadcrumb-active': loginMode === 'phone'}">手机号登录</span>
            </el-breadcrumb-item>
            <el-breadcrumb-item @click="changeLoginMode('wechat')">
              <span :class="{'breadcrumb-active': loginMode === 'wechat'}">微信扫码登录</span>
            </el-breadcrumb-item>
          </el-breadcrumb>

          <!-- 登录表单 -->
          <el-form :model="loginForm" :rules="loginRules" ref="loginFormRef" class="login-form" label-width="80px">
          <!-- 用户名或手机号 -->
            <el-form-item v-if="loginMode === 'username'" label="用户名" prop="userName">
              <el-input v-model="loginForm.userName" placeholder="请输入用户名" />
            </el-form-item>

            <el-form-item v-if="loginMode === 'phone'" label="手机号" prop="phone">
              <el-input v-model="loginForm.phone" placeholder="请输入手机号" />
            </el-form-item>

            <!-- 密码 -->
            <el-form-item v-if="loginMode !== 'wechat'" label="密码" prop="password">
              <el-input type="password" v-model="loginForm.password" placeholder="请输入密码" />
            </el-form-item>

            <!-- 验证码 -->
            <el-form-item v-if="loginMode === 'phone'" label="验证码" prop="code">
              <el-input v-model="loginForm.code" placeholder="请输入验证码" />
            </el-form-item>

            <!-- 微信扫码登录占位符 -->
            <div v-if="loginMode === 'wechat'" class="wechat-login-placeholder">
              <p>微信扫码登录功能暂未开发</p>
              <div class="wechat-placeholder">微信二维码占位</div>
            </div>

            <!-- 登录按钮 -->
            <el-form-item>
              <el-button type="primary" @click="handleLogin">登录</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <el-tab-pane label="注册" name="register">
          <!-- 注册表单 -->
          <el-form :model="registerForm" :rules="registerRules" ref="registerFormRef" class="register-form" label-width="80px">

          <el-form-item label="用户名" prop="userName">
              <el-input v-model="registerForm.userName" placeholder="请输入用户名" />
            </el-form-item>

            <el-form-item label="密码" prop="password">
              <el-input :type="passwordVisible ? 'text' : 'password'" v-model="loginForm.password" placeholder="请输入密码" autocomplete="off">
                <template #suffix>
                  <el-icon :class="{ 'password-toggle': true, 'visible': passwordVisible }" @click="togglePasswordVisibility">
                    <i v-if="passwordVisible" class="el-icon-view"></i>
                    <i v-else class="el-icon-view-off"></i>
                  </el-icon>
                </template>
              </el-input>

            </el-form-item>

            <el-form-item label="确认密码" prop="checkPassword">
              <el-input type="password" v-model="registerForm.checkPassword" placeholder="请再次输入密码" />
            </el-form-item>

            <el-form-item label="手机号" prop="phone">
              <el-input v-model="registerForm.phone" placeholder="请输入手机号" />
            </el-form-item>

            <el-form-item label="验证码" prop="code">
              <el-input v-model="registerForm.code" placeholder="请输入验证码" />
            </el-form-item>

            <!-- 注册按钮 -->
            <el-form-item>
              <el-button type="primary" @click="handleRegister">注册</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </el-container>
</template>

<script>
import { ElMessage } from 'element-plus';
import { loginByUserName } from '@/service/login/login.service.js'; // 确保路径与项目结构一致
import CryptoJS from 'crypto-js';

export default {
  name: 'LoginRegisterView',
  data() {
    return {
      // 控制密码是否可见
      passwordVisible: false,

      // 当前激活的 tab（'login' 或 'register'）
      activeTab: 'login',

      // 当前登录模式（'username'、'phone' 或 'wechat'）
      loginMode: 'username',

      //背景图url
      backgroundImg: '',

      // 登录表单的数据
      loginForm: {
        userName: '',
        password: '',
        phone: '',
        code: ''
      },

      // 登录表单验证规则
      loginRules: {
        userName: [{required: true, message: '请输入用户名', trigger: 'blur'}],
        password: [{required: true, message: '请输入密码', trigger: 'blur'}],
        phone: [{required: true, message: '请输入手机号', trigger: 'blur'}],
        code: [{required: true, message: '请输入验证码', trigger: 'blur'}]
      },

      // 注册表单的数据
      registerForm: {
        userName: '',
        password: '',
        checkPassword: '',
        phone: '',
        code: ''
      },

      // 注册表单验证规则
      registerRules: {
        userName: [{required: true, message: '请输入用户名', trigger: 'blur'}],
        password: [{required: true, message: '请输入密码', trigger: 'blur'}],
        checkPassword: [{required: true, message: '请再次输入密码', trigger: 'blur'}],
        phone: [{required: true, message: '请输入手机号', trigger: 'blur'}],
        code: [{required: true, message: '请输入验证码', trigger: 'blur'}]
      },
      aesKey: '03d91b9d753622b2', // AES 加密密钥，长度必须是 16/24/32 位
      aesIv: '03d91b9d753622b2'   // AES 加密初始化向量 (IV)
    };
  },
  mounted() {
    // 动态导入图片资源
    import('@/assets/login_background.png').then((module) => {
      this.backgroundImg = module.default;
    });
  },
  methods: {
    // 切换密码可见性
    togglePasswordVisibility() {
      this.passwordVisible = !this.passwordVisible;
    },

    // 处理 Tab 切换时的逻辑
    handleTabClick(tab) {
      if (tab.name === 'register') {
        this.loginMode = 'username';
      }
    },

    // 切换登录模式
    changeLoginMode(mode) {
      this.loginMode = mode;
    },

    handleLogin() {
      if (this.loginMode === 'username') {
        this.$refs.loginFormRef.validate((valid) => {
          if (valid) {
            try {
              // 使用 AES 加密密码
              const encryptedPassword = this.encryptPassword(this.loginForm.password);

              const loginParams = {
                userName: this.loginForm.userName,
                password: encryptedPassword // 发送加密后的密码
              };

              // 调用 loginByUserName，并通过回调方式处理结果
              loginByUserName(
                  loginParams,
                  (response) => {
                    // 成功回调
                    if (response.status === 'success') {
                      // 将 token 存储到 localStorage
                      const { token, expires } = response.data; // 获取 token 和过期时间

                      // 将 token 和过期时间存入 Cookie
                      this.setCookie('token', token, new Date(parseInt(expires, 10)));
                      this.setCookie('token_expires', expires, new Date(parseInt(expires, 10)));

                      // 设置 Axios 默认的请求头，带上 token
                      // this.$axios.defaults.headers.common['Authorization'] = `Bearer ${response.data.token}`;

                      console.log("请求已发送, 响应:", response);
                      ElMessage.success('登录成功！');

                      // 跳转到首页
                      this.$router.push({ name: 'home' });
                    } else {
                      ElMessage.error(`登录失败: ${response.message}`);
                    }
                  },
                  (error) => {
                    // 失败回调
                    ElMessage.error(`登录失败: ${error}`);
                  }
              );
            } catch (error) {
              ElMessage.error(`登录失败: ${error}`);
            }
          } else {
            ElMessage.error('请正确填写登录信息！');
          }
        });
      } else {
        ElMessage.warning('请使用用户名和密码登录！');
      }
    },

    setCookie(name, value, expires) {
      document.cookie = `${name}=${value};expires=${expires.toUTCString()};path=/`;
    },

    // 获取 Cookie 的方法
    getCookie(name) {
      const cookieArr = document.cookie.split('; ');
      for (const cookie of cookieArr) {
        const [key, val] = cookie.split('=');
        if (key === name) return val;
      }
      return null;
    },

    // 删除 Cookie 的方法
    deleteCookie(name) {
      document.cookie = `${name}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/`;
    },

    // AES 加密方法
    encryptPassword(password) {
      const key = CryptoJS.enc.Utf8.parse(this.aesKey);
      const iv = CryptoJS.enc.Utf8.parse(this.aesIv);
      const encrypted = CryptoJS.AES.encrypt(CryptoJS.enc.Utf8.parse(password), key, {
        iv: iv,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
      });
      return encrypted.toString(); // 返回加密后的字符串
    },

    // 处理注册操作
    handleRegister() {
      this.$refs.registerFormRef.validate((valid) => {
        if (valid) {
          ElMessage.success('注册成功！');
        } else {
          ElMessage.error('请正确填写注册信息！');
        }
      });
    }
  }
}
</script>


<style scoped>
/* 页面整体样式 */
.login-register-container {
  position: relative; /* 使子元素的定位生效 */
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;

}
.background-img {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: -1; /* 背景图片放在最底层 */
}
/* 登录和注册卡片样式 */
.login-card {
  width: 450px;
  padding: 20px;
  border-radius: 15px;
  background: rgba(255, 255, 255, 0.75); /* 设置卡片背景为半透明白色 */
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1); /* 较轻的阴影 */
  border: 1px solid rgba(0, 0, 0, 0.1); /* 边框颜色与背景图片匹配 */
}

/* 卡片标题样式 */
.login-card-header {
  text-align: center;
  margin-bottom: 20px;
}

.login-card-header h2 {
  margin: 0;
  font-size: 24px;
  font-weight: bold;
  color: #333;
}

.login-card-header p {
  margin: 0;
  font-size: 14px;
  color: #777;
}

.login-logo {
  width: 100px;
  height: 100px;
  margin-bottom: 0px;
}

/* 表单样式 */
.login-form,
.register-form {
  width: 100%;
}

/* 微信登录占位样式 */
.wechat-login-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin: 20px 0;
}

.wechat-placeholder {
  width: 200px;
  height: 200px;
  border: 1px dashed #ccc;
  border-radius: 4px;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #999;
}

/* 面包屑样式 */
.el-breadcrumb {
  margin-bottom: 20px;
  text-align: center;
}

.breadcrumb-active {
  font-weight: bold;
  color: #42b983;
}

/* 按钮样式 */
.el-button {
  width: 100%;
  margin-top: 20px;
}
</style>
